package com.assembly.oauth2.wechat;

import com.alibaba.druid.util.StringUtils;
import com.assembly.oauth2.CustomAuthenticationFailureHandler;
import com.assembly.oauth2.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component("weChatValidateFilter")
public class WeChatValidateFilter extends OncePerRequestFilter {
    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //判断请求地址
        log.info(request.getRequestURI()+"==============WeChatValidateFilter===================  "+request.getMethod());
        // 1. 判断 请求是否为手机登录，且post请求
        if("/auth/wx/form".equals(request.getRequestURI())
                && "post".equalsIgnoreCase(request.getMethod())) {
            try {
                // 校验验证码合法性
                 validate(request);
            }catch (AuthenticationException e) {
                // 交给失败处理器进行处理异常
                customAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                // 一定要记得结束
                return;
            }
        }
        // 放行
        filterChain.doFilter(request, response);
    }
    private void validate(HttpServletRequest request){
        String code = request.getParameter("code");
        //校验请求参数
        if(StringUtils.isEmpty(code)){
            log.info("validate{}===code为空==================");
            throw new ValidateCodeException("code不能为空");
        }


    }
}
